import { SetupContext, computed, toRefs, inject, ref, watch } from 'vue'
import { CheckboxEmit, CheckboxProps } from '../checkbox-types'
import { checkboxGroupInjectionKey } from '../checkbox-group-types'

export default function (props: CheckboxProps, ctx: SetupContext<CheckboxEmit>) {
  const checkboxGroupConf = inject(checkboxGroupInjectionKey, null)
  const { label, value, halfChecked } = toRefs(props)
  const direction = ref(props.direction)
  const disabled = ref(props.disabled)
  const isTitle = ref(props.isTitle)
  const changeHandle = (event: Event) => {
    checked.value = (event.target as HTMLInputElement).checked
    if (checkboxGroupConf && (event.target as HTMLInputElement).checked) {
      checkboxGroupConf?.checks.value.push(value.value)
    } else {
      checkboxGroupConf?.checks.value.splice(checkboxGroupConf?.checks.value.indexOf(value.value), 1)
    }
    ctx.emit('change', event)
  }
  const _checked = ref(false)
  const checked = computed({
    get() {
      return props.modelValue ?? _checked.value
    },
    set(val) {
      _checked.value = val
      if (props.modelValue !== undefined) {
        ctx.emit('update:modelValue', val)
      }
    }
  })
  checkboxGroupConf &&
    watch(
      () => checkboxGroupConf?.checks.value,
      (newValue) => {
        checked.value = !!checkboxGroupConf?.checks.value.includes(value.value)
      },
      {
        immediate: true,
        deep: true
      }
    )

  checkboxGroupConf && (direction.value = checkboxGroupConf?.direction.value!)
  checkboxGroupConf && (disabled.value = checkboxGroupConf?.disabled.value!)
  checkboxGroupConf && (isTitle.value = checkboxGroupConf?.isTitle.value!)

  return {
    label,
    value,
    halfChecked,
    isTitle,
    direction,
    disabled,
    checked,
    changeHandle
  }
}
